import { fileURLToPath, URL } from 'node:url';
import viteCompression from 'vite-plugin-compression';
import VueSetupExtend from 'vite-plugin-vue-setup-extend';
import eslint from 'vite-plugin-eslint2';
import AutoImport from 'unplugin-auto-import/vite';
import Components from 'unplugin-vue-components/vite';
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers';

import { type ConfigEnv, defineConfig, loadEnv } from 'vite';
import vue from '@vitejs/plugin-vue';
import vueJsx from '@vitejs/plugin-vue-jsx';
import path from 'node:path';
import fs from 'fs';

// https://vitejs.dev/config/
export default defineConfig(({ mode }: ConfigEnv) => {
  const env = loadEnv(mode, process.cwd());
  const envName = env.VITE_VUE_APP_ENV_NAME;
  const hasCustomRouter = env.VITE_CUSTOM_ROUTER === 'true' ? true : false;
  const hasCustomAppNav = env.VITE_CUSTOM_APP_NAV === 'true' ? true : false;
  const hasCustomStyle = env.VITE_CUSTOM_STYLES === 'true' ? true : false;

  const proxy =
    mode === 'development'
      ? {
          '/api': {
            target: env.VITE_BASE_URL,
            secure: false,
            headers: {
              Connection: 'keep-alive',
            },
            changeOrigin: true,
            rewrite: (path: string) => path.replace(/^\/api/, ''),
            configure: (proxy: {
              on: (arg0: string, arg1: (proxyRes: any) => void) => void;
            }) => {
              proxy.on('proxyRes', (proxyRes) => {
                const cookies = proxyRes.headers['set-cookie'];
                const tmp = [];
                if (cookies) {
                  for (const cookie of cookies) {
                    tmp.push(cookie + ';PATH=/');
                  }
                }
                proxyRes.headers['set-cookie'] = tmp;
              });
            },
          },
          '/ws': {
            target: 'wss://' + env.VITE_BASE_URL.split('//')[1],
            changeOrigin: true,
            secure: false,
            ws: true,
            rewrite: (path: string) => path.replace(/^\/ws/, ''),
          },
        }
      : {};

  // Set alias
  const alias: { [index: string]: string } = {};
  if (envName) {
    alias['@/assets/images/login-company-logo.svg'] = fileURLToPath(
      new URL(`./src/env/assets/images/${envName}-logo.png`, import.meta.url),
    );
    if (hasCustomRouter) {
      // If env has custom router, resolve routes in src/router/index.js
      alias['./routes'] = fileURLToPath(
        new URL(`./src/env/router/${envName}.ts`, import.meta.url),
      );
    }
    if (hasCustomAppNav) {
      alias['./HeaderNavigation'] = fileURLToPath(
        new URL(
          `./src/env/components/AppNavigation/${envName}.ts`,
          import.meta.url,
        ),
      );
      alias['../AppHeader/HeaderNavigation'] = fileURLToPath(
        new URL(
          `./src/env/components/AppNavigation/${envName}.ts`,
          import.meta.url,
        ),
      );
    }
    alias['@'] = fileURLToPath(new URL('./src', import.meta.url));
  } else {
    alias['@'] = fileURLToPath(new URL('./src', import.meta.url));
  }

  return {
    plugins: [
      vue(),
      vueJsx(),
      viteCompression(),
      VueSetupExtend(),
      eslint({
        include: [
          'src/**/*.js',
          'src/**/*.vue',
          'src/**/*.ts',
          'src/*.js',
          'src/*.vue',
          'src/*.ts',
        ],
      }),
      AutoImport({
        imports: [
          // 需要自动导入的插件，自定义导入的API
          'vue',
          'vue-router',
          'pinia',
        ],
        dts: './src/auto-imports.d.ts', // 指明 .d.ts 文件的位置和文件名
        resolvers: [ElementPlusResolver()],
      }),
      Components({
        resolvers: [ElementPlusResolver()],
      }),
    ],
    // Resolve unsafe-eval restriction.
    define: {
      __INTLIFY_JIT_COMPILATION__: JSON.stringify(true),
    },
    resolve: {
      alias,
    },
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: `@use "@/assets/styles/main.scss";`,
          api: 'modern-compiler',
        },
      },
    },
    server: {
      host: '0.0.0.0',
      port: 8000,
      open: false,
      https: {
        cert: fs.readFileSync(path.join(__dirname, 'keys/cert.crt')),
        key: fs.readFileSync(path.join(__dirname, 'keys/cert.key')),
      },
      proxy,
    },
  };
});
